<?php
namespace Leaps\Cache;

use Leaps\Base\Manager;

class CacheManager extends Manager {

	/**
	 * 创建APC缓存实例
	 *
	 * @return \Leaps\Cache\Adapter\Apc
	 */
	protected function createApcDriver()
	{
		return $this->repository(new Adapter\Apc());
	}

	/**
	 * 创建内存数组缓存实例
	 *
	 * @return \Leaps\Cache\Adapter\Array
	 */
	protected function createArrayDriver()
	{
		return $this->repository(new Adapter\Arrays());
	}

	/**
	 * 创建文件缓存驱动
	 *
	 * @return \Leaps\Cache\Adapter\File
	 */
	protected function createFileDriver()
	{
		$path = $this->app['config']['cache.path'];
		return $this->repository(new Adapter\File($this->app['files'], $path));
	}

	/**
	 * 创建WinCache缓存驱动
	 *
	 * @return \Leaps\Cache\Adapter\WwinCache
	 */
	protected function createWincacheDriver()
	{
	    return $this->repository(new Adapter\WinCache());
	}

	/**
	 * 创建redis缓存驱动
	 *
	 * @return \Leaps\Cache\Adapter\Redis
	 */
	protected function createRedisDriver()
	{
	    $redis = $this->app['redis'];
	    return $this->repository(new Adapter\Redis($redis));
	}

	/**
	 * 创建Memcache缓存驱动
	 *
	 * @return \Leaps\Cache\Adapter\Memcached
	 */
	protected function createMemcachedDriver()
	{
		$servers = $this->app['config']['cache.memcached'];
		$mamcached = $this->getMemcachedConnection($servers);
		return $this->repository(new Adapter\Memcached($mamcached));
	}

	/**
	 * 创建数据库缓存驱动
	 *
	 * @return \Leaps\Cache\Adapter\Database
	 */
	protected function createDatabaseDriver()
	{
		$connection = $this->getDatabaseConnection();
		$encrypter = $this->app['encrypter'];
		$table = $this->app['config']['cache.table'];
		return $this->repository(new Adapter\Database($connection, $encrypter, $table));
	}

	/**
	 * 创建Memcached连接
	 * @param array $servers 服务器
	 * @throws \RuntimeException
	 * @return \Memcached
	 */
	protected function getMemcachedConnection($servers){
	    $memcached = new \Memcached ();
	    foreach ( $servers as $server ) {
	        $memcached->addServer ( $server ['host'], $server ['port'], $server ['weight'] );
	    }
	    if ( $memcached->getVersion () === false ) {
	        throw new \RuntimeException ( "Could not establish Memcached connection." );
	    }
	    return $memcached;
	}

	/**
	 * 从数据库连接获得数据库驱动程序。
	 *
	 * @return \Leaps\Database\Connection
	 */
	protected function getDatabaseConnection()
	{
		$connection = $this->app['config']['cache.connection'];
		return $this->app['db']->connection($connection);
	}

	/**
	 * 创建一个新的缓存驱动实例
	 *
	 * @param  \Leaps\Cache\AdapterInterface  $store
	 * @return \Leaps\Cache\Repository
	 */
	protected function repository(AdapterInterface $store)
	{
		return new Repository($store);
	}

	/**
	 * 获取默认缓存驱动名称
	 *
	 * @return string
	 */
	protected function getDefaultDriver()
	{
		return $this->app['config']['cache.driver'];
	}

}